package it.terry.alarm;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;



public class AutoAlarmSender extends Thread {
	private static final String LOC_TAG = "CASPITA";
	private Context ctx;
	private AlarmManager alarmManager;
	private PendingIntent pendingIntent;
	private List<String> data;
	private Handler handler;

	public AutoAlarmSender(Context ctx, AlarmManager alarmManager,PendingIntent pendingIntent,Handler handler) {
		// TODO Auto-generated constructor stub
		this.alarmManager = alarmManager;
		this.ctx = ctx;
		this.pendingIntent = pendingIntent;
		this.handler = handler;
	}

	@Override
	public void run(){
		
		AssetManager am = ctx.getAssets();
		//prelievo
		try {

			data = new ArrayList<String>();
			InputStream is = am.open("tempi_allarme.txt");
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String line = null;
			while ((line = reader.readLine()) != null) {

				data.add(line);
			}
			Log.d(LOC_TAG, data.size() + " lines");
			Log.d(LOC_TAG, "Memorizzato"+data.toString());
	      
			 	} catch (IOException e) {

			e.printStackTrace();
		}

			 	//USCITA
		        for (String str: data) {
		        	
		            try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}	            
		            
		            // Setta la posizione
					Integer i = Integer.valueOf(str);
		            Log.d(LOC_TAG, "caspita"+ i);
		            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ (i * 1000), pendingIntent);
		            notifyMessage("Allarme settato: "+ i +"secondi restanti");
		        }
		 
		
	}
	private void notifyMessage(String stri) {
	    Message msg = handler.obtainMessage();
	    Bundle b = new Bundle();
	    b.putString("refresh", ""+stri);
	    msg.setData(b);
	    handler.sendMessage(msg);
	  }
	}

